package com.sgb.kjwl;

import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;


/**
 * Created by WYJ on 2020/8/19.
 *  建议使用Lib下的 AppLazyFragment
 */
@Deprecated
public abstract class AppLazyFragment extends AppFragment {

    protected boolean isPrepared;
    protected boolean isLazyLoaded;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isPrepared = true;
        initView();
        lazyLoad();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        disPatchVisibleHint(isVisibleToUser);
    }

    private void disPatchVisibleHint(boolean isVisibleToUser) {
        if (lazyLoad()) {
            return;
        }
        if (isPrepared && isLazyLoaded) {
            if (isVisibleToUser) {
                onVisible();
            } else {
                onInvisible();
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        disPatchVisibleHint(!hidden);
    }


    protected void initView() {

    }

    public boolean lazyLoad() {
        if (getUserVisibleHint() && isPrepared && !isLazyLoaded) {
            Fragment parentFragment = getParentFragment();
            boolean isParentUserVisible;
            if (parentFragment != null) {
                isParentUserVisible = parentFragment.getUserVisibleHint();
            } else {
                isParentUserVisible = true;
            }
            if (isParentUserVisible) { // 防止Fragment+Fragment模式 父Fragment初始化進入，子Fragment getUserVisibleHint==ture;
                isLazyLoaded = true;
                if(parentFragment != null){
                    Log.d("AppLazyFragment", "parentFragment :" + parentFragment.toString() );
                } else {
                    Log.d("AppLazyFragment", "parentFragment :" + "---");
                }
                onLazyLoad();
            }
            return true;
        }
        return false;
    }

    public void onVisible() {

    }

    protected abstract void onLazyLoad();

    public void onInvisible() {
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isPrepared = false;
        isLazyLoaded = false;
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {

    }
}
